from BoardCell import BoardCell

class CellCSPVariable:
    def __init__(self,father):
        self.father = father
        self.members = father.unknowns
        self._domain = None

    def getMines(self,solution):
        """For a given solution, return the mine coordinates from this
        variable."""
        mineCoordinates = []        
        i = 0
        for i in xrange(len(self.members)):
            coord = self.members[i].coordinate
            if solution[self][i] == 1 and not coord in mineCoordinates:
                mineCoordinates.append(coord)
            i+=1
        return mineCoordinates

    def getSafe(self,solution):
        """For a given solution, return the safe coordinates in this variable"""
        safeCoordinates = []
        i = 0
        for i in xrange(len(self.members)):
            coord = self.members[i].coordinate
            if solution[self][i] == 0 and not coord in safeCoordinates:
                safeCoordinates.append(coord)
            i+=1
        return safeCoordinates

    def domain(self):
        if not self._domain:
            nMines = self.father.value
            nMembers = len(self.members)
            self._domain = []
            self._recursiveDomainGenerator(nMines,self.members,0,[0]*nMembers)
        return self._domain
        
    def _recursiveDomainGenerator(self,nMines,members,depth,permutation):
        if depth == len(members):
            return
        else:
            for val in (1,0):
                permutation[depth] = val
                sum = 0
                for p in permutation:
                    sum+=p
                if sum > nMines:
                    return
                if sum == nMines:
                    if not permutation in self._domain:
                        self._domain.append(permutation[:])
                self._recursiveDomainGenerator(nMines,members,depth+1,permutation)
    
    def __repr__(self):
        return str(self.father.coordinate)
